package lab03.test08;

import java.io.*;
//8、	将文件一和文件二的内容合并成文件三，合并方法是：从文件一读取一个字节放入文件三，
// 再从文件二读取一个字节放入文件三，如此轮流直至某一个文件读完，
// 再将较长文件中的剩余部分读取放入至文件三。
public class Test08 {
    public static void main(String[] args) {

        //创建3个文件类对象
        File file1 = new File("D:\\dev\\lab03\\test08\\1.txt");
        File file2 = new File("D:\\dev\\lab03\\test08\\2.txt");
        File file3 = new File("D:\\dev\\lab03\\test08\\3.txt");

        //声明2个输入流对象
        FileInputStream fileInputStream1 = null;
        FileInputStream fileInputStream2 = null;
        //声明1个输出流对象
        FileOutputStream fileOutputStream3 = null;


        //读取1,2文件并合并
        try {
            fileInputStream1 = new FileInputStream(file1);
            fileInputStream2 = new FileInputStream(file2);
            fileOutputStream3 = new FileOutputStream(file3);

            //定义两个临时变量存储读取到的数据
            int temp1 = fileInputStream1.read();//返回类型为int
            int temp2 = fileInputStream2.read();

            while ((temp1 != -1) && (temp2 != -1)) {
                fileOutputStream3.write(temp1);
                fileOutputStream3.write(temp2);

                temp1 = fileInputStream1.read();
                temp2 = fileInputStream2.read();
            }

            if (temp1 == -1) {
                while (temp2 != -1) {
                    fileOutputStream3.write(temp2);
                    temp2 = fileInputStream2.read();
                }
            }
            if (temp2 == -1) {
                while (temp1 != -1) {
                    fileOutputStream3.write(temp1);
                    temp1 = fileInputStream1.read();
                }
            }

            System.out.println("文件合并完成！");


        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream1.close();
                fileInputStream2.close();
                fileOutputStream3.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }


    }
}
